package org.boulderfoodrescue.webapp.client.old.viewer.editaddress;

import java.util.Date;

import org.boulderfoodrescue.webapp.client.googlemap.GoogleMap;
import org.boulderfoodrescue.webapp.client.old.datamanager.DataManager;
import org.boulderfoodrescue.webapp.client.old.event.PlaceChangedEvent;
import org.boulderfoodrescue.webapp.shared.Place;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;

public class EditAddressPanel extends Composite {

  @UiField
  Label address_found_text1;
  @UiField
  Label address_found_text2;
  @UiField
  Button button_update_address;
  @UiField
  Button button_cancel_update;
  @UiField
  TextBox input_name;
  @UiField 
  DateBox date_box;
  @UiField
  ListBox ammount_food;
  protected Place current;
  protected boolean warned = false;
  protected GoogleMap gMap;
  protected EditDialogBox parent;
  
  private static EditAddressPanelUiBinder uiBinder = GWT
      .create(EditAddressPanelUiBinder.class);
  
  interface EditAddressPanelUiBinder extends
      UiBinder<Widget, EditAddressPanel> {
  }
  
  public EditAddressPanel(EditDialogBox parent, Place location, GoogleMap gMap) {
    this.parent = parent;
    this.gMap = gMap;
    initWidget(uiBinder.createAndBindUi(this));
    current = location;
    input_name.setText(current.getName());
    date_box.setValue(new Date(current.getExpiration_date()));
    ammount_food.setSelectedIndex(current.getAmount().intValue());
    address_found_text1.setText(location.topLineString());
    address_found_text2.setText(location.bottomLineString());
  }
  
  @UiHandler("button_update_address")
  public void onButtonSave(ClickEvent e){
    String name = input_name.getText();
    if(name.length() == 0){
      Window.alert("Name field cannot be empty");
      return;
    }
    long a_level = ammount_food.getSelectedIndex();
    current.setName(name);
    if(date_box.getValue() == null){
      Window.alert("The expiration date must be a valid date");
      return;
    }
    current.setExpiration_date(date_box.getValue().getTime());
    current.setAmount(a_level);

    DataManager.get().fireEvent(new PlaceChangedEvent(current, null));
    parent.addressInfoEntered();
  }

  @UiHandler("button_cancel_update")
  public void onButtonCancelSave(ClickEvent e){
    parent.addressInfoEntered();
  }
}